//引入angular核心组件
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

//引入类
import { Food } from '../../domain/food';
//引入服务
import { FoodService } from '../../service/food.service';

declare var layui: any;
@Component({
  selector: 'app-food-list',
  templateUrl: './food-list.component.html',
  styleUrls: ['./food-list.component.css'],
  providers: [FoodService]
})
export class FoodListComponent implements OnInit {

  foods: Food[];
  selectedFoodId: number;

  food: Food;
  foodCreate: Food;

  constructor(
    private foodService: FoodService,
    private router: Router,
    private location : Location
  ) { }

  ngOnInit() {

    layui.use(['element', 'layer', 'form'], function () {
      var element = layui.element;
      var layer = layui.layer;
      var form = layui.form;
      form.render();
      element.render('element');

      //监听折叠
      element.on('collapse(newFood)', function (data) {
        layer.msg('展开状态：' + data.show);
      });
    });

    //组件加载初期查询所有食物
    this.foodService.getFoods()
      .then(res => this.foods = res);

    this.foodCreate = new Food();
    this.food = new Food();
  }

  //选择一个食物
  isSelect(food: Food) {
    return food.id === this.selectedFoodId;
  }

  //路由到选择食物的详细页面
  onSelect(food: Food) {
    this.router.navigate(['/food-detail', food.id]);
  }

  //新建一个Food
  createFood(): void {
    this.foodService.createFood(this.foodCreate)
    .then(()=>{
      location.reload();
    });
  }

  //删除一个Food
  deleteFood(food: Food): void {
    this.foodService.deleteFood(food)
    .then(()=>{
      location.reload();
    });
  }

  //重置
  reset(): void {
    this.foodCreate = this.food;
  }


}
